//
//  RYYuSuyuanViewController.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/12.
//  Copyright © 2021 叁拾叁. All rights reserved.
//



import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then

class RYYuSuyuanViewController: SYBaseTableViewController, UITableViewDelegate {
    
    var id: Int!
    
    var model: RYProductDetailModel = RYProductDetailModel() {
        didSet {
            self.loadDataSuccessed()
        }
    }
    var bgView: EScrollPageItemBaseView = EScrollPageItemBaseView(pageTitle: "溯源记录")
    
    fileprivate var vm: VGTableViewPageViewModel<TraceRecords>!
    
    
    
    public var loboVC: RYYuViewController!
    
    public var canScroll: Bool = true {
        didSet {
            self.tableView.isScrollEnabled = canScroll
        }
    }

    
    init(id: Int) {
        super.init(nibName: nil, bundle: nil)
        self.id = id
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setTableView()
        setNoDataView()
        setupViewModel()
    }
    
    fileprivate func setupViewModel() {
        vm = VGTableViewPageViewModel<TraceRecords>()
        vm.tableView = tableView
        vm.emptyViewParams = ("", "", 40.0, 30.0)
        tableView.vg_pageProtocol = vm
//        vm.getList(type: .nongchangList(page: 1, size:10), dispose: dispose)
//        vm.getDataClosure = {[weak self] page in
//            if let `self` = self {
//                self.vm.getList(type: .nongchangList(page: self.vm.vg_pageNo, size:self.vm.size), dispose: self.dispose)
//            }
//        }
        vm.loadDataClosure = {[weak self] success in
            if let `self` = self {
                if success {
                    self.loadDataSuccessed()
                }
            }
        }
    }
    
    func loadDataSuccessed() {
        DispatchQueue.main.async {
            
            self.vm.dataSource = []
            if let r = self.model.traceRecords {
                
                for (_, value) in r.enumerated() {
                    self.vm.dataSource.append(value)
                    
                }
                self.setDataSource()
            }
        }
    }
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-BOTTOM_SAFE_HEIGHT - 41.autoWidth() - STATUSBAR_HEIGHT), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = Constant.bgViewColor
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.bgView)
        self.bgView.addSubview(self.tableView!)
        self.tableView.delegate = self
        self.tableView.bounces = false
        
        tableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
                if let `self` = self {
                    
                }
            })
            .disposed(by:dispose)
    }
    
    func setNoDataView() {
        noDataView = SYNoDataView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT))
        noDataView.isHidden = true
        tableView.addSubview(noDataView)
    }
    
    func setDataSource() {
        //初始化数据
        let sections = Observable.just([
            TraceRecordsSection(header: "", items: self.vm.dataSource)
        ])
        
        //创建数据源
        let dataSource = RxTableViewSectionedAnimatedDataSource<TraceRecordsSection>(
            //设置单元格
            configureCell: { ds, tv, ip, item in
                
                
                let cell: RYYuSuyuanCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                    as? RYYuSuyuanCell ?? RYYuSuyuanCell(style: .default, reuseIdentifier: "Cell")
                cell.configure(item, self.model.type == 1)
                cell.selectionStyle = .none
                return cell
                
                
                
            },
            //设置分区头标题
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
            })
        tableView.dataSource = nil
        //绑定单元格数据
        sections
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: dispose)
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let v = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 63.autoWidth()))
        let title = UILabel(frame: CGRect(x: 15, y: 12, width: SCREEN_WIDTH - 30, height: 14))
        title.text = "生产周期:\(self.model.productionCycle ?? 0)天"
        title.font = 14.autoBoldFontSize()
        title.textColor = UIColor(hex: 0x333333)
        let jingao = UILabel(frame: CGRect(x: 15, y: 33, width: SCREEN_WIDTH - 30, height: 12))
        jingao.text = "温馨提示：因农产品生产具有不可控性，请以实际状态为准。"
        jingao.font = 12.autoFontSize()
        jingao.textColor = UIColor(hex: 0xFFA800)
        v.addSubview(title)
        v.addSubview(jingao)
        v.backgroundColor = .white
        return v
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 63.autoWidth()
    }
    
}

//自定义Section
struct TraceRecordsSection {
    var header: String
    var items: [Item]
}

extension TraceRecordsSection : AnimatableSectionModelType {
    typealias Item = TraceRecords
    
    var identity: String {
        return header
    }
    
    init(original: TraceRecordsSection, items: [Item]) {
        self = original
        self.items = items
    }
}

extension TraceRecords: IdentifiableType {
    var identity: String {
        return id!
    }
    
    typealias Identity = String
}
